using Microsoft.Web.WebView2.WinForms;
using PaddleOCRSharp;
using SqlSugar;
using Sunny.UI;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using WinApp.Services;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace WinApp.Models
{
    /// <summary>
    /// 动作基类
    /// </summary>
    public abstract class ActionBase
    {
        // 定义动作完成事件
        public event EventHandler<ActionResult> Completed;

        // 触发完成事件
        protected void OnCompleted(ActionResult result)
        {
            Completed?.Invoke(this, result);
        }
        /// <summary>
        /// 操作ID，主键自增
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }

        public virtual string Name { get; set; }

        [SugarColumn(IsIgnore = true)]
        public int Delay { get; set; } = 1000; // 延迟时间（毫秒）

        protected WebView2 _webView2;

        [SugarColumn(IsIgnore = true)]
        public WebView2 WebView
        {
            set => _webView2 = value;
        }

        public abstract Task<ActionResult> ExecuteAsync(); // 异步执行动作，返回统一结果

        [SugarColumn(IsIgnore = true)]
        public string TypeString
        {
            get
            {
                switch(this.GetType().Name)
                {
                    case "ActionGroup":
                        return "动作群组";
                    case "ActionClick":
                        return "点击";
                    case "ActionOcr":
                        return "OCR识别";
                    case "ActionImageMatch":
                        return "图像匹配";
                    default:
                        return this.GetType().Name;
                }
            }
        }
    }

    /// <summary>
    /// 点击操作实体类
    /// </summary>
    [SugarTable("ActionClick")]
    public class ActionClick : ActionBase
    {
        /// <summary>
        /// 操作名称（唯一）
        /// </summary>
        [SugarColumn(Length = 50, IsNullable = false)]
        public override string Name { get; set; }

        /// <summary>
        /// X坐标
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int X { get; set; }

        /// <summary>
        /// Y坐标
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Y { get; set; }


        /// <summary>
        /// 滚动距离
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Scroll { get; set; } = 0;

        /// <summary>
        /// 粘贴文本
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string Text { get; set; }

        public override async Task<ActionResult> ExecuteAsync()
        {
            string desc = "点击";
            bool isSuccess = false;
            if (_webView2 != null)
            {
                Point p = _webView2.PointToScreen(Point.Empty);
                if (Scroll == 0)
                {
                    MouseHelper.Click(p.X + X, p.Y + Y);
                    if (!Text.IsNullOrEmpty())
                    {
                        await Task.Delay(50);
                        Clipboard.SetText(Text);
                        SendKeys.SendWait("^v");
                        desc = "粘贴";
                    }
                }
                else
                {
                    MouseHelper.Scroll(p.X + X, p.Y + Y, Scroll);
                    desc = $"滚动";
                }
                isSuccess = true;
            }
            ActionResult result = new ActionResult { IsSuccess = isSuccess, Descprition = $"{desc}>{Name}" };
            OnCompleted(result);
            if (Delay > 0) await Task.Delay(Delay);
            return result;
        }
    }

    /// <summary>
    /// OCR识别操作实体类
    /// </summary>
    [SugarTable("ActionOcr")]
    public class ActionOcr : ActionBase
    {
        /// <summary>
        /// 操作名称（唯一）
        /// </summary>
        [SugarColumn(Length = 50, IsNullable = false)]
        public override string Name { get; set; }

        /// <summary>
        /// X坐标
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int X { get; set; }

        /// <summary>
        /// Y坐标
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Y { get; set; }

        /// <summary>
        /// 宽度
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Width { get; set; }

        /// <summary>
        /// 高度
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Height { get; set; }

        /// <summary>
        /// 关联的ActionImageMatch对象
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(ActionImageMatch.ActionOcrId))]
        public List<ActionImageMatch> ActionImageMatches { get; set; }

        public override async Task<ActionResult> ExecuteAsync()
        {
            string ocrRst = string.Empty;
            bool isSuccess = false;
            if (_webView2 != null)
            {
                Bitmap bitmap = await AuxHelper.CaptureWebViewAsync(_webView2, X, Y, Width, Height);
                ocrRst = AuxHelper.RecognizeText(bitmap);
                isSuccess = true;
                if (Delay > 0) await Task.Delay(Delay);
            }

            string desc = $"识别>{Name}:{ocrRst}";
            
            ActionResult result = new ActionResult
            {
                IsSuccess = isSuccess,
                OcrResult = ocrRst,
                Descprition = desc
            };
            OnCompleted(result);

            return result;
        }        
    }

    /// <summary>
    /// 图像匹配操作实体类
    /// </summary>
    [SugarTable("ActionImageMatch")]
    public class ActionImageMatch : ActionBase
    {
        /// <summary>
        /// 操作名称（唯一），由ActionOcr名称+识别+Avatar名称组成
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public override string Name
        {
            get
            {
                return $"{ActionOcr?.Name}识别{Avatar?.Name}";
            }
        }

        /// <summary>
        /// 头像ID，关联QueueAvatar表
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int AvatarId { get; set; }

        /// <summary>
        /// 匹配阈值
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public double Threshold { get; set; }

        /// <summary>
        /// 匹配区域
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int ActionOcrId { get; set; }

        /// <summary>
        /// 关联的Avatar对象
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(AvatarId))]
        public Avatar Avatar { get; set; }

        /// <summary>
        /// 关联的ActionOcr对象
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(ActionOcrId))]
        public ActionOcr ActionOcr { get; set; }

        public override async Task<ActionResult> ExecuteAsync()
        {
            bool isMatched = false;
            string rst = string.Empty;
            double matchScore = 0;
            Rectangle matchRect = new Rectangle();
            bool isSuccess = false;
            if (_webView2 != null)
            {
                Bitmap avatar = (Bitmap)Image.FromStream(new MemoryStream(Convert.FromBase64String(Avatar.Image)));
                Bitmap region = await AuxHelper.CaptureWebViewAsync(_webView2, ActionOcr.X, ActionOcr.Y, ActionOcr.Width, ActionOcr.Height);
                (isMatched, matchScore, matchRect) = AuxHelper.MatchAvatar(avatar, region, Threshold);
                isSuccess = true;
            }
            if (Delay > 0) await Task.Delay(Delay);
            rst = isMatched ? $"✔" : "✖";
            string desc = $"匹配>{Name}:{rst}";
            ActionResult result = new ActionResult
            {
                IsSuccess = isSuccess,
                IsMatched = isMatched,
                MatchScore = matchScore,
                MatchRect = matchRect,
                Descprition = desc
            };
            OnCompleted(result);
            return result;
        }
    }

    public class ActionDelay : ActionBase
    {
        public override async Task<ActionResult> ExecuteAsync()
        {
            ActionResult result = new ActionResult
            {
                IsSuccess = true,
                Descprition = $"等待>{Delay/1000}秒"
            };
            await Task.Delay(Delay);
            OnCompleted(result);
            return result;
        }
    }

    /// <summary>
    /// 头像队列实体类
    /// </summary>
    [SugarTable("Avatar")]
    public class Avatar
    {
        /// <summary>
        /// 头像ID，主键自增
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }

        /// <summary>
        /// 头像名称（唯一）
        /// </summary>
        [SugarColumn(Length = 50, IsNullable = false)]
        public string Name { get; set; }

        /// <summary>
        /// 头像图片数据（Base64格式）
        /// </summary>
        [SugarColumn(Length = -1, IsNullable = false)]
        public string Image { get; set; }

        /// <summary>
        /// 关联的ActionImageMatch对象
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(ActionImageMatch.AvatarId))]
        public List<ActionImageMatch> ActionImageMatches { get; set; }
    }

    public class ActionResult
    {
        public bool IsSuccess { get; set; } // 是否成功
        public string OcrResult { get; set; } // OCR识别结果
        public bool? IsMatched { get; set; } // 图像匹配是否成功
        public double? MatchScore { get; set; } // 图像匹配度
        public Rectangle MatchRect { get; set; } // 图像匹配位置
        public string Descprition { get; set; }
    }

    #region ActionGroup
    /// <summary>
    /// ActionGroup 类型
    /// </summary>
    public enum ActionGroupType
    {
        Sequential,  // 顺序执行
        Branch,      // 分支执行
        Loop,        // 循环执行
        FixedCount   // 定次运行
    }

    /// <summary>
    /// 参数类型
    /// </summary>
    public enum ParameterType
    {
        Ocr,    // OCR 识别结果
        Match,  // 图像匹配结果
        Const   // 常量
    }

    /// <summary>
    /// 条件类型
    /// </summary>
    public enum ConditionType
    {
        GreaterThan,        // 大于
        LessThan,           // 小于
        Equal,              // 等于
        NotEqual,           // 不等于
        Contains,           // 包含
        NotContains,        // 不包含
        GreaterThanOrEqual, // 大于等于
        LessThanOrEqual     // 小于等于
    }

    /// <summary>
    /// ActionGroup 类
    /// </summary>
    [SugarTable("ActionGroup")]
    public class ActionGroup : ActionBase
    {
        /// <summary>
        /// 名称
        /// </summary>
        [SugarColumn(Length = 50, IsNullable = false)]
        public override string Name { get; set; }
        /// <summary>
        /// ActionGroup 类型
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public ActionGroupType GroupType { get; set; }

        /// <summary>
        /// 第一组参数类型
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public ParameterType? Param1Type { get; set; }

        /// <summary>
        /// 第一组参数值
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string Param1Value { get; set; }

        /// <summary>
        /// 第二组参数类型
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public ParameterType? Param2Type { get; set; }

        /// <summary>
        /// 第二组参数值
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string Param2Value { get; set; }

        /// <summary>
        /// 条件类型
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public ConditionType? Condition { get; set; }

        /// <summary>
        /// 条件类型
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public bool IsDaily { get; set; } = false;

        /// <summary>
        /// 子 Action 列表
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(ActionGroupItem.ActionGroupId))]
        public List<ActionGroupItem> ActionGroupItems { get; set; }

        public override async Task<ActionResult> ExecuteAsync()
        {
            ActionResult result = new ActionResult();
            if (GroupType == ActionGroupType.Sequential)
            {
                // 顺序执行
                foreach (var item in ActionGroupItems.OrderBy(x => x.Sequence))
                {
                    ActionBase ac = item.Action;
                    ac.WebView = _webView2;
                    ac.Completed += (sender, args) => OnCompleted(args);
                    var actionResult = await ac.ExecuteAsync();
                    if (!actionResult.IsSuccess)
                    {
                        result.IsSuccess = false;
                        return result;
                    }
                }
                result.IsSuccess = true;
                result.Descprition = $"顺序执行>{Name}:{ActionGroupItems.Count}";
            }
            else if (GroupType == ActionGroupType.Branch || GroupType == ActionGroupType.Loop || GroupType == ActionGroupType.FixedCount)
            {
                // 分支执行或循环执行或定次运行
                bool conditionResult = await EvaluateCondition();
                
                if (GroupType == ActionGroupType.Branch)
                {
                    string cdRst = conditionResult? "✔" : "✖";
                    // 分支执行
                    var actions = conditionResult
                        ? ActionGroupItems.Where(x => x.Group == 1).OrderBy(x => x.Sequence)
                        : ActionGroupItems.Where(x => x.Group == 0).OrderBy(x => x.Sequence);

                    foreach (var item in actions)
                    {
                        ActionBase ac = item.Action;
                        ac.WebView = _webView2;
                        var actionResult = await ac.ExecuteAsync();
                        if (!actionResult.IsSuccess)
                        {
                            result.IsSuccess = false;
                            result.Descprition = actionResult.Descprition;
                            return result;
                        }
                    }
                    result.Descprition = $"判断执行>{Name}: {cdRst}";
                    result.IsSuccess = true;
                }
                else if (GroupType == ActionGroupType.Loop)
                {
                    int i = 0;
                    // 循环执行
                    while (conditionResult)
                    {
                        foreach (var item in ActionGroupItems.OrderBy(x => x.Sequence))
                        {
                            i++;
                            ActionBase ac = item.Action;
                            ac.WebView = _webView2;
                            ac.Completed += (sender, args) => OnCompleted(args);
                            var actionResult = await ac.ExecuteAsync();
                            if (!actionResult.IsSuccess)
                            {
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                        conditionResult = await EvaluateCondition();
                    }
                    result.Descprition = $"循环执行>{Name}:{i}";
                    result.IsSuccess = true;
                }
                else if (GroupType == ActionGroupType.FixedCount)
                {
                    // 定次运行
                    if (Param1Type == ParameterType.Const && !string.IsNullOrEmpty(Param1Value))
                    {
                        int count;
                        if (int.TryParse(Param1Value, out count))
                        {
                            for (int i = 0; i < count; i++)
                            {
                                foreach (var item in ActionGroupItems.OrderBy(x => x.Sequence))
                                {
                                    ActionBase ac = item.Action;
                                    ac.WebView = _webView2;
                                    ac.Completed += (sender, args) => OnCompleted(args);
                                    var actionResult = await ac.ExecuteAsync();
                                    if (!actionResult.IsSuccess)
                                    {
                                        result.IsSuccess = false;
                                        result.Descprition = actionResult.Descprition;
                                        return result;
                                    }
                                }
                            }
                            result.Descprition = $"定次执行>{Name}:{count}";
                            result.IsSuccess = true;
                        }
                        else
                        {
                            result.IsSuccess = false;
                            result.Descprition = $"定次执行>{Name}:非整数";
                        }
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Descprition = $"定次执行>{Name}:非常量";
                    }
                }
            }
            OnCompleted(result);
            return result;
        }
       
        /// <summary>
        /// 评估条件
        /// </summary>
        private async Task<bool> EvaluateCondition()
        {
            if (Param1Type == null || Param2Type == null || Condition == null)
                return false;

            dynamic value1 = await GetParameterValue(Param1Type.Value, Param1Value);
            dynamic value2 = await GetParameterValue(Param2Type.Value, Param2Value);
            if( value1.GetType() != value2.GetType())
                return false;
            switch (Condition.Value)
            {
                case ConditionType.GreaterThan:
                    return value1 > value2;
                case ConditionType.LessThan:
                    return value1 < value2;
                case ConditionType.Equal:
                    return value1 == value2;
                case ConditionType.NotEqual:
                    return value1 != value2;
                case ConditionType.Contains:
                    return value1.Contains(value2);
                case ConditionType.NotContains:
                    return !value1.Contains(value2);
                case ConditionType.GreaterThanOrEqual:
                    return value1 >= value2;
                case ConditionType.LessThanOrEqual:
                    return value1 <= value2;
                default:
                    return false;
            }
        }

        /// <summary>
        /// 获取参数值
        /// </summary>
        private async Task<dynamic> GetParameterValue(ParameterType type, string value)
        {
            if (type == ParameterType.Const)
            {
                if(value.ToLower() == "true")
                    return true;
                else if (value.ToLower() == "false")
                    return false;
                return MatchNumberOrString(value);
            }
            else if (type == ParameterType.Ocr)
            {
                var ocrAction = DataHelper.GetActionOcrById(int.Parse(value));
                ocrAction.WebView = _webView2;
                ocrAction.Completed += (sender, args) => OnCompleted(args);
                var ocrResult = await ocrAction.ExecuteAsync();
                return MatchNumberOrString(ocrResult.OcrResult);
            }
            else if (type == ParameterType.Match)
            {
                var matchAction = DataHelper.GetActionImageMatchById(int.Parse(value));
                matchAction.WebView = _webView2;
                matchAction.Completed += (sender, args) => OnCompleted(args);
                var matchResult = await matchAction.ExecuteAsync();
                return matchResult.IsMatched;
            }
            return null;
        }

        public dynamic MatchNumberOrString(string input)
        {
            // 使用正则表达式提取数字部分（包括整数和浮点数）
            string numberPattern = @"-?\d+(\.\d+)?";
            Match match = Regex.Match(input, numberPattern);

            if (match.Success)
            {
                string numberString = match.Value;

                // 匹配整数
                string integerPattern = @"^-?\d+$";
                if (Regex.IsMatch(numberString, integerPattern))
                {
                    return int.Parse(numberString); // 返回整数
                }

                // 匹配浮点数
                string floatPattern = @"^-?\d+(\.\d+)?$";
                if (Regex.IsMatch(numberString, floatPattern))
                {
                    return double.Parse(numberString); // 返回浮点数
                }
            }

            // 如果没有匹配到数字，返回原始字符串
            return input;
        }
    }
    #endregion

    #region ActionGroupItem
    public enum ActionType
    {
        ActionGroup,
        ActionClick,
        ActionOcr,
        ActionImageMatch,
        ActionDelay
    }
    /// <summary>
    /// ActionGroupItem 类
    /// </summary>
    [SugarTable("ActionGroupItem")]
    public class ActionGroupItem
    {
        /// <summary>
        /// 主键
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }

        /// <summary>
        /// 关联的 ActionGroup ID
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int ActionGroupId { get; set; }

        /// <summary>
        /// 执行顺序
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Sequence { get; set; }

        /// <summary>
        /// 关联的 Action ID
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int ActionId { get; set; }

        /// <summary>
        /// 分组（用于分支执行）
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public int Group { get; set; } = 1;


        /// <summary>
        /// 动作类型
        /// </summary>
        [SugarColumn(IsNullable = false)]
        public ActionType ActionType { get; set; }


        [SugarColumn(IsIgnore = true)]
        public string ActionTypeName
        {
            get
            {
                switch (ActionType)
                {
                    case ActionType.ActionGroup:
                        return "动作群组";
                    case ActionType.ActionClick:
                        return "点击动作";
                    case ActionType.ActionOcr:
                        return "Ocr识别";
                    case ActionType.ActionImageMatch:
                        return "头像匹配";
                    case ActionType.ActionDelay:
                        return "延时";
                    default:
                        return "";
                }
            }
        }

        /// <summary>
        /// 关联的 Action 对象，根据 ActionType 和 ActionId 获取相应的实例
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public ActionBase Action
        {
            get
            {
                switch (ActionType)
                {
                    case ActionType.ActionGroup:
                        return DataHelper.GetActionGroupById(ActionId);
                    case ActionType.ActionClick:
                        return DataHelper.GetActionClickById(ActionId);
                    case ActionType.ActionOcr:
                        return DataHelper.GetActionOcrById(ActionId);
                    case ActionType.ActionImageMatch:
                        return DataHelper.GetActionImageMatchById(ActionId);
                    case ActionType.ActionDelay:                        
                        return DataHelper.GetActionDelay(ActionId);
                    default:
                        return null;
                }
            }
        }

        [SugarColumn(IsIgnore = true)]
        public string ActionName
        {
            get
            {
                if (Action != null)
                {
                    return Action.Name;
                }
                return "";
            }
        }
    }
    #endregion
}